package com.csair.platform.cit.service.util;

import com.csair.platform.cit.facade.exception.CitBizException;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;

public class ValidatorUtils {
    private static Validator validator;
    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param obj 待校验对象
     * @param groups 待校验的组
     * @throws CitBizException 校验不通过，则报CitBizException异常
     */
    public static void validateEntity(Object obj, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj, groups);
        if (!constraintViolations.isEmpty()) {
            constraintViolations.forEach(o -> {
                throw new CitBizException(7009, o.getMessage());
            });
        }
    }
    /**
     * 校验集合
     *
     * @param list 待校验集合
     * @param groups 待校验的组
     * @throws CitBizException 校验不通过，则报CitBizException异常
     */
    public static void validateList(List list, Class<?>... groups){
        if(CollectionUtils.isEmpty(list)){
            throw new CitBizException(7009, "请填写数据");
        }
        for (Object obj:list) {
            validateEntity(obj,groups);
        }
    }
}